/*
	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Library General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
*/

#include "styleeditorimpl.h"

#include <QtGui>

//
StyleEditorImpl::StyleEditorImpl( QWidget * parent, Qt::WFlags f)
        : QDialog(parent, f)
{
    setupUi(this);
	
    connect(this, SIGNAL(finished(int )), this, SLOT(onFinished(int )));

	laEditionStyleName->setText("");		  

    // Color tool button
    currentColor = QColor(Qt::black);
    drawColor(currentColor);   
}
//


void StyleEditorImpl::on_tbFontColor_clicked()
{
    QColor col = QColorDialog::getColor(currentColor, this);
    if (!col.isValid())
        return;

    drawColor(col);
    currentColor = col;

	updatePreview();
}

void StyleEditorImpl::drawColor(QColor color)
{
    QPixmap pix(16, 16);
    pix.fill(color);
    tbFontColor->setIcon(pix);
}

void StyleEditorImpl::fillComboSize()
{
    // Fill size combo.
    QFontDatabase db;
    foreach(int size, db.standardSizes())
    cbFontSize->addItem(QString::number(size));
    cbFontSize->setCurrentIndex(cbFontSize->findText(QString::number(QApplication::font().pointSize())));
}

void StyleEditorImpl::initCombos()
{
	fillComboSize();
	
	int defaultFontIndex = cbFont->findText(m_confManager->defaultFont);
	if (defaultFontIndex != -1)
		cbFont->setCurrentIndex(defaultFontIndex);
		
	int defaultFontSizeIndex = cbFontSize->findText(m_confManager->defaultFontSize);
	if (defaultFontSizeIndex != -1)
		cbFontSize->setCurrentIndex(defaultFontSizeIndex);
		
	m_defaultFont = cbFont->currentIndex();
    m_defaultFontSize = cbFontSize->currentIndex();
}

void StyleEditorImpl::setManagers(ConfigurationManager *confManager, StyleManager *styleManager)
{
    m_styleManager = styleManager;
    m_confManager = confManager;
    
    updateStyleList();
    // Font size combo
    initCombos();
}

void StyleEditorImpl::updateStyleList()
{
    QListWidgetItem *item;
    lwStyle->clear();
    int count = m_styleManager->getStyleCount();

    for (int i = 0; i < count; i++)
    {
        item = new QListWidgetItem(m_styleManager->getStyleName(i), lwStyle, 0);
        item->setData(Qt::UserRole, i);
        lwStyle->addItem(item);
    }
}

void StyleEditorImpl::updateModelFromUI(int index)
{
    // Font
    m_styleManager->setStyleFont(index, cbFont->currentText());

    // Font size
    m_styleManager->setStyleSize(index, cbFontSize->currentText());

    // Font color
    m_styleManager->setStyleColor(index, currentColor);

    // Style
    m_styleManager->setStyleBold(index, ckBold->isChecked());
    m_styleManager->setStyleItalic(index, ckItalic->isChecked());
    m_styleManager->setStyleUnderline(index, ckUnderline->isChecked());

    // Alignment
    int alignIndex;
    if (rbLeft->isChecked())
        alignIndex = 0;
    else if (rbCenter->isChecked())
        alignIndex = 1;
    else if (rbRight->isChecked())
        alignIndex = 2;
    else if (rbJustify->isChecked())
        alignIndex = 3;
    else
        alignIndex = 0;

    m_styleManager->setStyleAlignment(index, alignIndex);
}

void StyleEditorImpl::updatePreview()
{
	QFont currentFont = laPreview->font();
	currentFont.setFamily(cbFont->currentText());
	currentFont.setPointSize(QString(cbFontSize->currentText()).toInt());
	
	currentFont.setBold(ckBold->isChecked());
	currentFont.setItalic(ckItalic->isChecked());
	currentFont.setUnderline(ckUnderline->isChecked());
	
	laPreview->setFont(currentFont);
	
	laPreview->setText("<font color=\"" + currentColor.name() + "\">" + tr("The quick brown fox jumps over the lazy dog.") + "</font>");
}

void StyleEditorImpl::updateUIFromModel(int index)
{
    // Font
    int fontIndex = cbFont->findText(m_styleManager->getStyleFont(index));
    if (fontIndex != -1)
        cbFont->setCurrentIndex(fontIndex);
    else
        cbFont->setCurrentIndex(m_defaultFont);

    // Font size
    int sizeIndex = cbFontSize->findText(m_styleManager->getStyleSize(index));
    if (sizeIndex != -1)
        cbFontSize->setCurrentIndex(sizeIndex);
    else
        cbFontSize->setCurrentIndex(m_defaultFontSize);

    // Font color
    currentColor = m_styleManager->getStyleColor(index);
    drawColor(currentColor);

    // Style
    ckBold->setChecked(m_styleManager->getStyleBold(index));
    ckItalic->setChecked(m_styleManager->getStyleItalic(index));
    ckUnderline->setChecked(m_styleManager->getStyleUnderline(index));

    // Alignment
    switch (m_styleManager->getStyleAlignment(index))
    {
    case 0 :
        rbLeft->setChecked(true);
        break;
    case 1 :
        rbCenter->setChecked(true);
        break;
    case 2 :
        rbRight->setChecked(true);
        break;
    case 3 :
        rbJustify->setChecked(true);
        break;
    default :
        rbLeft->setChecked(true);
        break;
    }
    
    tbSelectStyle->setChecked(m_styleManager->isStyleSelected(index));
}

void StyleEditorImpl::on_lwStyle_currentItemChanged(QListWidgetItem* current, QListWidgetItem* previous)
{
    if (previous != NULL)
    {
        int index = previous->data(Qt::UserRole).toUInt();
        updateModelFromUI(index);
    }

    if (current != NULL)
    {
        int index = current->data(Qt::UserRole).toUInt();
        updateUIFromModel(index);

        laEditionStyleName->setText(m_styleManager->getStyleName(index));

        int listIndex = lwStyle->currentRow();
        if (listIndex == 0)
            tbMoveUp->setEnabled(false);
        else
            tbMoveUp->setEnabled(true);

        if (listIndex == (lwStyle->count() - 1))
            tbMoveDown->setEnabled(false);
        else
            tbMoveDown->setEnabled(true);

        tbRemoveStyle->setEnabled(true);
        tbSelectStyle->setEnabled(true);

    }
    else
    {
        laEditionStyleName->setText("");
        tbRemoveStyle->setEnabled(false);
        tbMoveUp->setEnabled(false);
        tbMoveDown->setEnabled(false);
    }
    updatePreview();
}

void StyleEditorImpl::onFinished(int result)
{
    QListWidgetItem *currentItem;
    currentItem = lwStyle->currentItem();
    if (currentItem != NULL)
    {
        int index = currentItem->data(Qt::UserRole).toUInt();
        updateModelFromUI(index);
    }
    m_styleManager->updateModelWithCurrentList(lwStyle);
}

void StyleEditorImpl::on_tbAddStyle_clicked()
{
    bool ok;
    QString newName = QInputDialog::getText(this, tr("New style"),
                                            tr("New style name :"), QLineEdit::Normal, tr("NewStyle"), &ok);

    if (ok)
    {
		if (!m_styleManager->doStyleExists(newName))
		{
			int index = m_styleManager->addStyle(newName, cbFont->itemText(m_defaultFont), cbFontSize->itemText(m_defaultFontSize));

			QListWidgetItem *item = new QListWidgetItem(newName, lwStyle, 0);
			item->setData(Qt::UserRole, index);
			lwStyle->addItem(item);
			lwStyle->setCurrentItem(item);
		}
		else
			QMessageBox::information(this, tr("Warning"), tr("Style already exists."), QMessageBox::Ok);
    }
}

void StyleEditorImpl::on_tbRemoveStyle_clicked()
{
    QListWidgetItem *item = lwStyle->currentItem();
    if (item != NULL)
    {
        QMessageBox::StandardButton ret = QMessageBox::question(this, tr("Delete"), tr("Do you want to delete this style ?"),
                                          QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel);

        if (ret == QMessageBox::Ok)
        {
            // Delete the item, but NOT its data in the model, as it will create an offset
            // with index which will mess up the whole thing ;)
            delete item;
        }
    }
}

void StyleEditorImpl::on_tbMoveUp_clicked()
{
    int listIndex = lwStyle->currentRow();
    if (listIndex > 0)
    {
        QListWidgetItem *item = new QListWidgetItem(*lwStyle->currentItem());
        delete lwStyle->currentItem();
        lwStyle->insertItem(listIndex - 1, item);
        lwStyle->setCurrentItem(item);
    }
}

void StyleEditorImpl::on_tbMoveDown_clicked()
{
    int listIndex = lwStyle->currentRow();
    if (listIndex < (lwStyle->count() - 1))
    {
        QListWidgetItem *item = new QListWidgetItem(*lwStyle->currentItem());
        delete lwStyle->currentItem();
        lwStyle->insertItem(listIndex + 1, item);
        lwStyle->setCurrentItem(item);
    }
}

void StyleEditorImpl::on_tbSelectStyle_clicked()
{
	int index = lwStyle->currentItem()->data(Qt::UserRole).toUInt();
	m_styleManager->setStyleSelected(index, tbSelectStyle->isChecked());
}

void StyleEditorImpl::on_cbFont_currentIndexChanged(int index)
{
	updatePreview();
}

void StyleEditorImpl::on_ckBold_clicked()
{
	updatePreview();
}

void StyleEditorImpl::on_ckItalic_clicked()
{
	updatePreview();
}

void StyleEditorImpl::on_ckUnderline_clicked()
{
	updatePreview();
}

void StyleEditorImpl::on_cbFontSize_currentIndexChanged(int index)
{
	updatePreview();
}
